package logger2.formatter;

import java.text.SimpleDateFormat;
import java.util.Date;

import logger2.LogRecord;

public class ConfigurableLogFormatter implements LogFormatter {
	private final SimpleDateFormat sdf;
	private final String model;
	private final long timeOffset;
	
	public ConfigurableLogFormatter(String model, String dateFormat, long timeOffset) {
		super();
		this.model = model;
		sdf = new SimpleDateFormat(dateFormat);
		this.timeOffset = timeOffset;
	}
	
	public ConfigurableLogFormatter(String model, String dateFormat) {
		this(model, dateFormat, 0);
	}
	
	@Override
	public String format(LogRecord record) {
		String tmp = model;
		
		int t = tmp.indexOf("%d");
		tmp = tmp.substring(0, t) + sdf.format(new Date(record.getTime()-timeOffset)) + tmp.substring(t+2);
		
		t = tmp.indexOf("%l");
		tmp = tmp.substring(0, t) + record.getLogger() + tmp.substring(t+2);
		
		t = tmp.indexOf("%L");
		tmp = tmp.substring(0, t) + record.getLvl() + tmp.substring(t+2);
		
		t = tmp.indexOf("%m");
		tmp = tmp.substring(0, t) + record.getMessage() + tmp.substring(t+2);
		
		t = tmp.indexOf("%t");
		tmp = tmp.substring(0, t) + record.getThreadName() + tmp.substring(t+2);
		
		t = tmp.indexOf("%T");
		tmp = tmp.substring(0, t) + record.getStackTraceElement() + tmp.substring(t+2);
		
		return tmp;
	}
}
